package online.afeibaili.storebackendframework.controller;

import online.afeibaili.storebackendframework.model.AdminInfo;
import online.afeibaili.storebackendframework.server.AdminInfoServer;
import online.afeibaili.storebackendframework.util.Sh256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminExcController {
    private final AdminInfoServer adminInfoServer;
    Logger log = LoggerFactory.getLogger(ProductAdminController.class);

    public AdminExcController(AdminInfoServer adminInfoServer) {
        this.adminInfoServer = adminInfoServer;
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> loginInfo) {
        AdminInfo adminInfo = new AdminInfo();
        adminInfo.setUser(loginInfo.get("user"));
        String token = Sh256.getSha256Hash(loginInfo.get("user")+loginInfo.get("password"));
        adminInfo.setToken(token);
        if (adminInfoServer.count() > 0) {
            log.info("管理员已存在无法注册");
            return ResponseEntity.ok(Map.of("code", 200, "message", "管理员已存在无法注册"));
        }
        String result = adminInfoServer.insert(adminInfo)==1 ? "注册成功" : "注册失败";
        log.info("{}:{}", result, token);
        return ResponseEntity.ok(Map.of("code", 200, "result",result));
    }
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginInfo) {
        AdminInfo adminInfo = adminInfoServer.selectByToken(loginInfo.get("user"), loginInfo.get("password"));
        log.info("{}:{}", adminInfo == null ? "登录失败" : "登录成功", adminInfo == null ? "请检查账号密码" : adminInfo.getToken());
        return adminInfo == null ? ResponseEntity.ok(Map.of("code", 200, "message", "账号或密码不正确")) :
                ResponseEntity.ok(Map.of("code", 200, "message", "登录成功", "token", adminInfo.getToken(), "user", adminInfo.getUser()));
    }


}